package com.lmxdawn.api.common.autoconfigure;

import com.lmxdawn.api.common.filter.CacheRequestFilter;
import com.lmxdawn.api.common.filter.RequestParamFilter;
import com.lmxdawn.api.common.session.PermissionInterceptor;
import com.lmxdawn.api.common.session.RedisSessionStrategy;
import com.lmxdawn.api.common.session.SessionInterceptor;
import com.lmxdawn.api.common.session.SessionStrategy;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.Duration;
import java.util.List;

/**
 * web 配置
 *
 * @author jy
 * @since 2023-12-06 16:40
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(SessionProperties.class)
public class WebConfiguration implements WebMvcConfigurer {
    
    private SessionProperties properties;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 不拦截的URL
        List<String> ignoreUrls = properties.getIgnoreUrls();
        ignoreUrls.add("/error");
        registry.addInterceptor(new SessionInterceptor()).excludePathPatterns(ignoreUrls).addPathPatterns("/web/**").order(1);
        registry.addInterceptor(new PermissionInterceptor()).excludePathPatterns(ignoreUrls).addPathPatterns("/web/**").order(2);
    }
    
    @Bean("RedisSession")
    public SessionStrategy sessionStrategy() {
        return new RedisSessionStrategy();
    }
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(50))
                .setReadTimeout(Duration.ofSeconds(50))
                .build();
    }
    /**
     * 创建 CacheRequestFilter Bean，可重复读取请求内容
     */
    @Bean
    public FilterRegistrationBean<CacheRequestFilter> requestCacheFilter() {
        CacheRequestFilter cacheRequestFilter = new CacheRequestFilter();
        FilterRegistrationBean<CacheRequestFilter> bean = new FilterRegistrationBean<>(cacheRequestFilter);
        bean.setOrder(Integer.MIN_VALUE);
        return bean;
    }
    
    /**
     * 创建 RequestParamFilter Bean，读取请求内容
     */
    @Bean
    public FilterRegistrationBean<RequestParamFilter> requestParamFilter() {
        RequestParamFilter requestParamFilter = new RequestParamFilter();
        FilterRegistrationBean<RequestParamFilter> bean = new FilterRegistrationBean<>(requestParamFilter);
        bean.setOrder(Integer.MIN_VALUE + 100);
        return bean;
    }

}
